﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Clipping.Infrastructure.Models;
using System.IO;
using System.Xml.Linq;
namespace Clipping.Utils
{
    public class MediaInfoProvider
    {
        private static MediaInfoProvider instance = new MediaInfoProvider();

        private string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", "MediaList.xml");

        private bool mediaInfoReady = false;

        private List<MediaInfo> allMediaInfos;

        public static MediaInfoProvider GetInstance()
        {
            return instance;
        }


        public bool IsClientInfoDownloaded()
        {
            return File.Exists(path);
        }

        public List<MediaInfo> GetAllMediaInfo()
        {
            if (!mediaInfoReady)
                tryReadMediaInfo();
            return this.allMediaInfos;
        }

        private void tryReadMediaInfo()
        {
            if (System.IO.File.Exists(path))
            {
                string fileContent = System.IO.File.ReadAllText(path, Encoding.UTF8);
                this.allMediaInfos = parse(fileContent);
            }
        }

        private List<MediaInfo> parse(string fileContent)
        {
            List<MediaInfo> rtn = new List<MediaInfo>();

            int i = fileContent.IndexOf("<");
            if (i != 0)
                fileContent = fileContent.Substring(i);

            XDocument xDoc = XDocument.Parse(fileContent, LoadOptions.None);
            var mediaNodes = xDoc.Descendants("Medias").First().Descendants("Media");

            foreach (var mediaNode in mediaNodes)
            {
                MediaInfo mediaInfo = Parse(mediaNode);
                rtn.Add(mediaInfo);
            }
            return rtn;

        }

        private MediaInfo Parse(XElement mediaNode)
        {
            MediaInfo rtn = new MediaInfo();
            rtn.Id = ReadValueStr(mediaNode, "Id");
            rtn.Name = ReadValueStr(mediaNode, "Name");
            rtn.Url = ReadValueStr(mediaNode, "Url");
            return rtn;
        }

        protected static string ReadValueStr(XElement node, string propertyName)
        {
            if (node.Attribute(propertyName) != null)
            {
                var rtn = node.Attribute(propertyName).Value;
                if (!string.IsNullOrEmpty(rtn))
                    return rtn.Trim();
                    return null;
            }
            else
            {
                return null;
            }
        }


    }
}
